//
//  WKNavigationDelegateNormal.swift
//  LXReuseTools
//
//  Created by yoctech on 2021/8/12.
//

import UIKit
import WebKit

public class WKNavigationDelegateNormal: NSObject {

}

extension WKNavigationDelegateNormal: WKNavigationDelegate {
    // 页面开始加载时调用
    public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){

    }
    
    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let urlStr = navigationAction.request.url?.absoluteString ?? ""
        print("加载网页地址:\(urlStr)")
        
        if let scheme = navigationAction.request.url?.scheme {
            if scheme == "https" || scheme == "http" {
                decisionHandler(WKNavigationActionPolicy.allow)
                return
            }
            decisionHandler(WKNavigationActionPolicy.cancel)
            
            if let url = navigationAction.request.url, UIApplication.shared.canOpenURL(url) {
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                } else {
                    UIApplication.shared.openURL(url)
                }
            }
            return
        }
        decisionHandler(WKNavigationActionPolicy.allow)
    }
    
    public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        let urlStr = navigationResponse.response.url?.absoluteString ?? ""
        print("响应网页地址:\(urlStr)")
        decisionHandler(WKNavigationResponsePolicy.allow)
    }
        
    // 当内容开始返回时调用
    public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
        
    }
    // 页面加载完成之后调用
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        
    }
    // 页面加载失败时调用
    public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){
        
    }
}
